package com.efounder.presenter;

import android.content.DialogInterface;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.activity.MallVirtualProductSelectionPayActivity;
import com.efounder.adapter.MallSelectionPayMultiAdapter;
import com.efounder.bean.MallSelectionPayMultipleBean;
import com.efounder.bean.MallSelectionPayOrderBean;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.DialogUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.efounder.mvp.base.BasePresenterImpl;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.EthTokenTransactionManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.VirtualTransferUtils;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ORDER_SELECT_PAY_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/5 17:11
 * @desc : 虚拟商品的选择支付界面
 * @version: 1.0
 */
public class MallVirtualProductSelectionPayPresenter extends BasePresenterImpl<MallVirtualProductSelectionPayActivity> {


    public MallVirtualProductSelectionPayPresenter(MallVirtualProductSelectionPayActivity view) {
        super(view);
    }

    /**
     * 请求订单详情接口
     *
     * @param userID  手机号
     * @param orderId 订单编号
     */
    public void getOrderDetailsData(String userID, String orderId) {
        view.showProgress(mContext.getString(R.string.dialog_title_progress_hint));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orderIds", orderId);
        MallRequestUtil.getRequest(TAG, ORDER_SELECT_PAY_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                if (view != null) {
//                    LogUtils.e("asd测试-----》" + response);
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    try {

                        MallSelectionPayOrderBean mallSelectionPayOrderBean = gson.fromJson(response, MallSelectionPayOrderBean.class);
                        view.getDataSuccess(mallSelectionPayOrderBean, getDataMultiple(mallSelectionPayOrderBean));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onFail(String error) {
                if (view != null) {
                    view.dismissProgress();
                }
            }
        });
    }

    /**
     * 选择支付加载列表数据
     *
     * @return 数据
     */
    public List<MallSelectionPayMultipleBean> getDataMultiple(MallSelectionPayOrderBean mallSelectionPayOrderBean) {
        List<MallSelectionPayMultipleBean> mallSelectionPayMultipleBeans = new ArrayList<>();
        for (MallSelectionPayOrderBean.PrePayInfoBean.TokenUseArrayBean tokenUseArrayBean : mallSelectionPayOrderBean.getPrePayInfo().getTokenUseArray()) {
            //现在不支持多个产品一起支付，判断当前支付金额是否和抵扣金额相等
            if (tokenUseArrayBean.getRmbValue() == mallSelectionPayOrderBean.getPrePayInfo().getOrdersTotalPrice()) {
                MallSelectionPayMultipleBean.SelectionPay selectionPay = new MallSelectionPayMultipleBean.SelectionPay();
                selectionPay.setPay(true);
                selectionPay.setTitle(tokenUseArrayBean.getTokenTypeName());
                selectionPay.setTokenIcon(tokenUseArrayBean.getTokenIcon());
                selectionPay.setSurplusNum("");
                selectionPay.setRmbValue(tokenUseArrayBean.getRmbValue() + "");
                selectionPay.setTokenAmount(tokenUseArrayBean.getTokenAmount() + "");
                selectionPay.setTokenTypeId(tokenUseArrayBean.getTokenTypeId());
                mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.PAY_WAY_ITEM
                        , tokenUseArrayBean.getTokenTypeId(), selectionPay));
            }
        }
//        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.OTHER_RECHARGE_WAY_TEXT
//                , new MallSelectionPayMultipleBean.SelectionPay(mContext.getResources().getString(R.string.mall_selection_pay_other_pay), R.mipmap.default_img, false, "0")));
//        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.OTHER_RECHARGE_WAY_ITEM
//                , MallSelectionPayMultipleBean.ALI_PAY, new MallSelectionPayMultipleBean.SelectionPay(mContext.getResources().getString(R.string.mall_selection_pay_ali_pay)
//                , R.drawable.alipay, true, "")));
//        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.OTHER_RECHARGE_WAY_ITEM
//                , MallSelectionPayMultipleBean.WX_PAY, new MallSelectionPayMultipleBean.SelectionPay(mContext.getResources().getString(R.string.mall_selection_pay_wx_pay)
//                , R.drawable.wxpay, true, "")));
        return mallSelectionPayMultipleBeans;
    }


    /**
     * adapter item中点击事件的逻辑处理
     *
     * @param adapter                   适配器
     * @param selectionPayMultipleBeans 实体类
     * @param position                  点击位置
     */
    public void onAdapterItemClick(BaseQuickAdapter adapter, List<MallSelectionPayMultipleBean> selectionPayMultipleBeans
            , int position) {
        MallSelectionPayMultipleBean selectionPayMultipleBean = selectionPayMultipleBeans.get(position);
        //根据判断显示隐藏check图片
        //当前item是否能支付，可以支付继续向下走
        if (selectionPayMultipleBean.getSelectionPay().isPay()) {
            //循环列表
            for (int i = 0; i < selectionPayMultipleBeans.size(); i++) {
                //选择两个
//                if (i == position) {
//                    if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
//                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(false);
//                    } else {
//                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(true);
//                    }
//                } else if (adapter.getItemViewType(i) == selectionPayMultipleBean.getItemType()) {
//                    selectionPayMultipleBeans.get(i).getSelectionPay().setSelectPayWay(false);
//                }
//                //  选择一个
                //如果循环到当前点击位置，根据当前的选择状态设置，如果不是全部设置为false
                if (i == position) {
                    if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(false);
                    } else {
                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(true);
                    }
                } else {
                    selectionPayMultipleBeans.get(i).getSelectionPay().setSelectPayWay(false);
                }

            }
            adapter.notifyDataSetChanged();
        }
    }


    /**
     * 支付订单
     */
    public void pay(final String fromAddress, final String toAddress, final String money, final String uuid, final String goodsId, final String orderBh,
                    final String goodNum, final String userId, final String contractAddress, final String gasPrice1) {

        PassWordAlertDialog dialog = new PassWordAlertDialog(mContext,
                new PassWordAlertDialog.OnEnterClick() {
                    @Override
                    public void passVerifySuccess(String passWord) {
                        startVirtualProductPay(fromAddress, toAddress, money, uuid, goodsId, orderBh, goodNum, userId, contractAddress, gasPrice1);
                    }
                });
        dialog.setCanCancle(true);
        dialog.show();


    }


    void startVirtualProductPay(String fromAddress, String toAddress, String money, String uuid, String goodsId, String orderBh,
                                String goodNum, String userId, String contractAddress, String gasPrice1) {
        view.showProgress(mContext.getString(R.string.dialog_title_progress_hint));
        VirtualTransferUtils.getInstance().startVirtualProductTransfer(mContext, fromAddress, toAddress, money, uuid, goodsId, orderBh, goodNum, userId, contractAddress, gasPrice1, new EthTokenTransactionManager.TransactionCallBack<Object>() {
            @Override
            public void transactionResult(boolean isSuccess, Object result) {
                view.dismissLoading();
                if (isSuccess) {
                    DialogUtil.showDialogNoCancel(mContext, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    view.paySuccess(null);
                                }
                            },R.string.common_text_hint,mContext.getString(R.string.mall_win_treasure_pay_result_success_hint)
                            ,mContext.getString(R.string.mail_sure));
                } else {
                    view.payFailed(null, ResStringUtil.getString(R.string.mobile_mall_pay_fail), 0);
                }
            }
        });
    }

    @Override
    public void detachView() {
        view.dismissProgress();
        super.detachView();
        EFHttpRequest.cancelRequest(TAG);
        //关闭交易
        VirtualTransferUtils.getInstance().closeTransaction();

    }


    /**
     * 加载各个积分数据抵扣的方法
     *
     * @param selectionPayMultipleBeans
     * @param ordersTotalPrice
     * @param balanceData
     * @param type
     */
    public void loadBalanceData(List<MallSelectionPayMultipleBean> selectionPayMultipleBeans
            , double ordersTotalPrice, String balanceData, String type
            , MallSelectionPayMultiAdapter mallSelectionPayMultiAdapter) {
        //循环列表获取对应的积分
        for (MallSelectionPayMultipleBean selectionPayMultipleBean : selectionPayMultipleBeans) {

//            if (selectionPayMultipleBean.getPayType().equals(type)) {

            String tokenAmount = selectionPayMultipleBean.getSelectionPay().getTokenAmount() + "";
//            balanceData = selectionPayMultipleBean.getSelectionPay().getSurplusNum();
            //判断当前积分数量和商品价格
            if (Double.valueOf(balanceData.replaceAll("[, ]","")) >= Double.valueOf(tokenAmount)) {
                //如果积分大于价格  显示抵扣信息  否则显示余额不足，不能支付
                String rmbValue;
                selectionPayMultipleBean.getSelectionPay().setPay(true);
//                    rmbValue = selectionPayMultipleBean.getSelectionPay().getRmbValue() + "";
//                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(tokenAmount
//                            + mContext.getString(R.string.mall_selection_pay_integral_deduction)
//                            + rmbValue + mContext.getString(R.string.mall_selection_pay_yuan));
                selectionPayMultipleBean.getSelectionPay().setPayStatusHint(mContext.getString(R.string.mall_selection_pay_integral_hint)
                        + " " + type + TCMathUtil.retainAsignDecimalsWithZero(Double.valueOf(tokenAmount), 2) + " ");
            } else {
                selectionPayMultipleBean.getSelectionPay().setPay(false);
                selectionPayMultipleBean.getSelectionPay().setPayStatusHint(mContext.getString(R.string.mall_selection_pay_integral_hint)
                        + " " + type + TCMathUtil.retainAsignDecimalsWithZero(Double.valueOf(tokenAmount), 2)  + " " + " (" + mContext.getString(R.string.mall_selection_pay_balance_hint) + ")");
            }
            //加载积分余额
            if (balanceData.contains(".")) {
                selectionPayMultipleBean.getSelectionPay().setSurplusNum(balanceData);
            } else {
                selectionPayMultipleBean.getSelectionPay().setSurplusNum(BalanceUtil.formatPrice(Double.valueOf(balanceData), true, 0));
            }

//            }
        }
        //更新当前item
        mallSelectionPayMultiAdapter.notifyDataSetChanged();

    }


    private void showPassDialog(final String tokenId, final String amount, final String orderIds) {
        PassWordAlertDialog dialog = new PassWordAlertDialog(mContext,
                new PassWordAlertDialog.OnEnterClick() {
                    @Override
                    public void passVerifySuccess(String passWord) {
//                        checkOutWithToken(tokenId,amount,orderIds);
                    }
                });
        dialog.setCanCancle(true);
        dialog.show();
    }

    /**
     * 获取余额
     * @param
     * @param contractAddress 合约地址
     */
    public void getBalancefromServer(String contractAddress) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userAddress", EnvironmentVariable.getProperty("tc_ethAddress", ""));
        map.put("contractAddress",contractAddress);
        TCRequestUtil.postCommonRequest(TAG, "mallCard/getBalanceByAddress", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                view.dismissProgress();
                LogUtils.e(TAG+"----->"+response);
                JSONObject jsonObject = null;

                try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                        String balance = jsonObject.getString("balance");
//                        balance = BalanceUtil.balanceConvert(balance);
                        if(balance!=null&& !balance.equals("")){
                            balance = TCMathUtil.retainAsignDecimalsWithZero(Double.valueOf(balance), 2);
                        }
                        if (view != null) {
                            view.getBalanceDataSuccess(balance);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                view.dismissProgress();
                ToastUtils.showShort(mContext.getString(R.string.mail_get_data_fail_again));
            }
        });
    }

}
